<?php

namespace App\Models;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Laravel\Passport\HasApiTokens;

class Users extends Authenticatable
{
    use Notifiable,HasApiTokens;

    const ADMIN_ID = 1;//超级管理员
    const ADMIN_0 = 0;//普通
    const ADMIN_1 = 1;//管理员
    protected $table = 'users';
    protected $fillable = [
        'openid', 'password', 'avatar','username','integral','register_at','login_at','is_admin','score'
    ];

    protected $hidden = [
        'password'
    ];
    const UPDATED_AT = 'login_at';
    const CREATED_AT = 'register_at';
    protected $dates = ['register_at','login_at'];


    protected function register($data){
        if(isset($data['password'])){
            $data['password'] = bcrypt($data['password']);
        }
        $data['is_admin'] = self::ADMIN_1;
        $user = $this->create($data);
        if($user === false){
            return false;
        }
        return $user;
    }

    /**
     * passport默认使用email字段作为用户名，如果usename是其他字段必须重新定义findForPassport方法，
     * 且必须是public
     * @param $username
     * @return mixed
     */
    public function findForPassport($username)
    {
        return self::where('openid', $username)->first();
    }


    /**
     * 更新任务积分
     * @param int $uid
     * @param string $type
     * @param int $times
     */
    public function updateTaskScore($uid = 0, $type = '',$times = 0){
        if($type){
            $maximum_times = config('task.maximum_times.'.$type);
            if($type == 'invite_friends' and $times <= $maximum_times){
                $score = config('task.score_rule.invite_friends.'.(string)($times-1));
                $this->where('id',$uid)->increment('score',$score);
            }elseif($times <= $maximum_times){
                $score = config('task.score_rule.'.$type);
                $this->where('id',$uid)->increment('score',$score);
            }
        }
    }

}
